import alert from './index.vue'
alert.install = function (Vue) {

  function create(Component, props) {
    return new Promise((resolve, reject) => {
      //方式一:使用Vue.extend创建
      const Ctor = Vue.extend(Component);
      //创建组件实例
      const alertDom = new Ctor({
        propsData: {
          config: props
        }
      })
      //挂载
      alertDom.$mount();
      console.log(document,'娃哈哈')
      document.body.appendChild(alertDom.$el); //把元素追加到body后面
      setTimeout(() => {
        alertDom.$el.classList.add("show")
      }, 50)
      alertDom.flag = false
      //监听组件的transitionend事件等动画结束后从dom移除并销毁组件
      function handleTransitionend(e) {
        if (alertDom.flag && e.target.classList.contains('zc-alert')) {
          document.body.removeChild(alertDom.$el) //移除元素
          alertDom.$destroy() //销毁
        }
      }
      //监听过度动画
      alertDom.$el.addEventListener("transitionend", handleTransitionend)
      alertDom.$el.addEventListener("webkitTransitionEnd", handleTransitionend)
      //移除弹窗组件
      alertDom.remove = () => {
        alertDom.$el.classList.remove("show");
        alertDom.flag = true
      }
      //取消按钮事件处理
      alertDom.cancel = (res) => {
        reject(res)
        alertDom.remove()
      }
      //确定按钮事件处理
      alertDom.confirm = (res) => {
        resolve(res)
        alertDom.remove()
      }
    })
  }
  Vue.prototype.$alert = (obj) => {
    return create(alert, obj)
  }
  Vue.prototype.$confirm = (obj) => {
    return create(alert, {
      type: 'confirm',
      ...obj
    })
  }
};

export default alert
